import { View, Text, Map, Button } from "@tarojs/components";
import { useEffect, useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";

import {
  AtModal,
  AtModalContent,
  AtModalAction,
  AtButton,
  AtList,
  AtListItem,
  AtFloatLayout,
  AtActionSheet,
  AtActionSheetItem,
  AtMessage,
  AtModalHeader,
  AtInput,
  AtPagination
} from "taro-ui";

import {
  getPointListApi,
  deletePointApi,
  bindPointApi,
  unbindPointApi,
  getAreaApi
} from "../../../utils/api";
import { btq } from "../../../utils/to";

import { baseUrl } from "../../../utils/http";

import "./index.scss";

import { useSelector, useDispatch } from "react-redux";

// 报警类型
const warnObj = {
  1: "无",
  2: "正常",
  3: "蚁情",
  4: "入侵",
  5: "低电量",
  9: "其他"
};
// 检查状态 1-正常；2-发现蚁情；3-发现蚁情但量不多，需再观察；4-发现蚁情但已撤离，无需灭杀；5-装置异常；6-装置被入侵破坏；7-装置丢失；8-装置被移位；9-其他
const inspectStateObj = {
  0: "无",
  1: "正常",
  2: "发现蚁情",
  3: "发现蚁情但量不多，需再观察",
  4: "发现蚁情但已撤离，无需灭杀",
  5: "装置异常",
  6: "装置被入侵破坏",
  7: "装置丢失",
  8: "装置被移位",
  9: "其他"
};
// 措施类型 1-无操作；2-简单恢复；3-替换电池；4-替换装置；5-灭蚁；6-推迟灭蚁(再观察)；9-其他
const inspectMeasureObj = {
  0: "无",
  1: "无操作",
  2: "简单恢复",
  3: "替换电池",
  4: "替换装置",
  5: "灭蚁",
  6: "推迟灭蚁(再观察)",
  9: "其他"
};

// 设备类型 1-半自动；2-全自动;3-机械式。
const deviceObj = {
  1: "半自动",
  2: "全自动",
  3: "机械式"
};

const Index = () => {
  const router = useRouter();

  const satellite = useSelector(state => state.yq.satellite);
  const dispatch = useDispatch();

  const [actionOpen, setActionOpen] = useState(false);

  // 布点列表
  const [pointList, setPointList] = useState([]);

  // 点击得那个布点得信息
  const [pointInfo, setPointInfo] = useState({});

  // 确认删除
  const [modalOpen, setModelOpen] = useState(false);

  const [markers, setmarkers] = useState([]);

  // 过滤
  const [filterOpen, set_filterOpen] = useState(false);
  const [filterValue, set_filterValue] = useState("");
  const [filtering, set_filtering] = useState(false);

  const [lnglat, set_lnglat] = useState([]);
  const [size, set_size] = useState(16);

  // 第几页
  const [currentPage, setCurrentPage] = useState(1);
  // 每页条数
  const [pageSize, setPageSize] = useState(10);
  // 总数
  const [total, setTotal] = useState(0);

  useDidShow(() => {
    getList();
    if (+router.params.longitude === 0) {
      set_size(10);
      getAreaApi({
        code: Taro.getStorageSync("code")
      }).then(res => {
        set_lnglat(btq(+res.record.lng, +res.record.lat));
      });
    } else {
      set_lnglat(
        btq(
          +router.params.longitude / 1000000,
          +router.params.latitude / 1000000
        )
      );
    }
  });

  // 获取数据
  const getList = async keyword => {
    const res = await getPointListApi({
      project_id: router.params.id,
      get_count: pageSize,
      start_index: pageSize * (currentPage - 1),
      point_keyword: keyword || ""
    });
    if (res.res === 0) {
      setTotal(res.total_count);
      setPointList(res.records);
      const mks = res.records.map(item => {
        const arr = btq(item.longitude / 1000000, item.latitude / 1000000);
        if (item.state === 1) {
          return {
            latitude: arr[1],
            longitude: arr[0],
            title:
              "布点名称:" +
              item.name +
              "\n上次报警类型:" +
              warnObj[item.warn_type] +
              "\n检查状态:" +
              inspectStateObj[item.inspect_state] +
              "\n检查方式:" +
              inspectMeasureObj[item.inspect_measure],
            iconPath: baseUrl + "/static/icon_red.png",
            width: 40,
            height: 60
          };
        } else {
          return {
            latitude: arr[1],
            longitude: arr[0],
            title:
              "布点名称:" +
              item.name +
              "\n上次报警类型:" +
              warnObj[item.warn_type] +
              "\n检查状态:" +
              inspectStateObj[item.inspect_state] +
              "\n检查方式:" +
              inspectMeasureObj[item.inspect_measure],
            iconPath: baseUrl + "/static/icon_green.png",
            width: 40,
            height: 60
          };
        }
      });
      if (keyword) {
        set_filtering(true);
        Taro.setNavigationBarTitle({
          title: "过滤中(" + keyword + ")..."
        });
      } else {
        set_filtering(false);
        Taro.setNavigationBarTitle({
          title: "布点列表"
        });
      }
      set_filterValue("");
      set_filterOpen(false);
      setmarkers(mks);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 分页切换
  const pageChange = e => {
    setCurrentPage(e.current);
  };

  useEffect(() => {
    getList();
  }, [currentPage]);

  const open = item => {
    setPointInfo(item);
    setActionOpen(true);
  };

  const actionClose = () => {
    setActionOpen(false);
  };

  // 查看详情
  const gotoDetail = () => {
    setActionOpen(false);
    Taro.navigateTo({
      url: "/pages/point_detail/index?id=" + pointInfo.point_id
    });
  };

  const gotoLonlat = () => {
    setActionOpen(false);
    Taro.navigateTo({
      url:
        "/pages/point_coordinate/index?lon=" +
        pointInfo.longitude +
        "&lat=" +
        pointInfo.latitude +
        "&id=" +
        pointInfo.point_id +
        "&pid=" +
        router.params.id
    });
  };

  // 删除布点
  const deletePoint = async () => {
    setActionOpen(false);
    setModelOpen(true);
  };

  // 关闭删除modal
  const closeModal = () => {
    setModelOpen(false);
  };

  const confirmModal = async () => {
    const res = await deletePointApi({
      point_id: pointInfo.point_id
    });
    if (res.res === 0) {
      Taro.atMessage({
        message: "删除成功",
        type: "success"
      });
      setModelOpen(false);
      getList();
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const goToPointAdd = () => {
    Taro.navigateTo({
      url:
        "/pages/packagec/point_add/index?id=" +
        router.params.id +
        "&lng=" +
        lnglat[0] +
        "&lat=" +
        lnglat[1]
    });
  };

  const goToBatch = () => {
    setActionOpen(false);
    Taro.navigateTo({
      url: "/pages/point_add_batch/index?id=" + router.params.id
    });
  };

  const gotoChange = () => {
    setActionOpen(false);
    Taro.navigateTo({
      url: "/pages/point_change/index?id=" + pointInfo.point_id
    });
  };

  const scanCode = () => {
    Taro.scanCode({
      success: res => {
        let result = res.result;
        if (result[0] !== "{") {
          result = "{" + result;
        }
        try {
          const json = JSON.parse(result);
          const { id, type, ver } = json;
          bindPointApi({
            point_id: pointInfo.point_id,
            device_code: id,
            device_type: type,
            device_tag: ver
          }).then(res => {
            if (res.res === 0) {
              setActionOpen(false);
              Taro.atMessage({
                message: "绑定成功",
                type: "success"
              });
              getList();
            } else {
              Taro.atMessage({
                message: res.msg,
                type: "warning"
              });
            }
          });
        } catch {
          Taro.atMessage({
            message: "二维码格式错误",
            type: "warning"
          });
        }
      }
    });
  };

  // 过滤
  const openFilter = () => {
    if (!filtering) {
      set_filterOpen(true);
    } else {
      getList();
    }
  };

  const cancelFilter = () => {
    set_filterOpen(false);
  };

  const closeFilter = () => {
    set_filterOpen(false);
  };

  const confirmFilter = () => {
    set_filterOpen(false);
    getList(filterValue);
  };

  const filterChange = value => {
    set_filterValue(value);
  };

  // 解绑
  const unbindDevice = async () => {
    const res = await unbindPointApi({
      point_id: pointInfo.point_id
    });
    if (res.res === 0) {
      setActionOpen(false);
      Taro.atMessage({
        message: "设备解绑成功",
        type: "success"
      });
      getList();
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const changeSatellite = () => {
    dispatch({ type: "changeSatellite" });
  };

  return (
    <View>
      <Map
        longitude={+lnglat[0]}
        latitude={+lnglat[1]}
        style={{ width: "100%", height: 300 }}
        scale={size}
        markers={markers}
        enable-satellite={satellite}
      ></Map>

      <View className="button-wrap">
        <View className="button-item" onClick={openFilter}>
          {filtering ? "取消过滤" : "布点过滤"}
        </View>
        <View className="button-item" onClick={goToPointAdd}>
          新建布点
        </View>
        <View className="button-item" onClick={goToBatch}>
          批量新建
        </View>
        <View className="button-item" onClick={changeSatellite}>
          {satellite ? "切换标准地图" : "切换卫星地图"}
        </View>
      </View>

      <View className="at-article__h2">布点列表</View>

      <AtList>
        {pointList.map(item => {
          return (
            <AtListItem
              title={item.name}
              arrow="right"
              // extraText={
              //   item.state === 1
              //     ? "停用"
              //     : item.device_type
              //     ? "启用(" +
              //       deviceObj[item.device_type] +
              //       // item.device_code +
              //       ")"
              //     : "启用"
              // }
              onClick={() => open(item)}
            />
          );
        })}
      </AtList>

      <AtPagination
        total={total}
        pageSize={pageSize}
        current={currentPage}
        onPageChange={pageChange}
      />

      <AtActionSheet
        isOpened={actionOpen}
        cancelText="取消"
        onClose={actionClose}
        onCancel={actionClose}
      >
        <AtActionSheetItem onClick={gotoDetail}>查看详情</AtActionSheetItem>
        {pointInfo.device_code ? (
          <AtActionSheetItem onClick={unbindDevice}>解绑设备</AtActionSheetItem>
        ) : (
          <AtActionSheetItem onClick={scanCode}>绑定设备</AtActionSheetItem>
        )}
        <AtActionSheetItem onClick={gotoLonlat}>修改经纬度</AtActionSheetItem>
        <AtActionSheetItem onClick={gotoChange}>修改信息</AtActionSheetItem>
        <AtActionSheetItem onClick={deletePoint}>删除布点</AtActionSheetItem>
      </AtActionSheet>

      {/* 过滤弹框 */}
      <AtModal isOpened={filterOpen} onClose={closeFilter}>
        <AtModalHeader>工程筛选</AtModalHeader>
        <AtModalContent>
          <AtInput
            name="value"
            title="关键字"
            type="text"
            value={filterValue}
            onChange={filterChange}
          />
        </AtModalContent>
        <AtModalAction>
          {" "}
          <Button onClick={cancelFilter}>取消</Button>{" "}
          <Button onClick={confirmFilter}>确定</Button>{" "}
        </AtModalAction>
      </AtModal>

      {/* 删除确认 */}
      <AtModal isOpened={modalOpen} closeOnClickOverlay={false}>
        <AtModalContent>您确定要删除这个布点吗?</AtModalContent>
        <AtModalAction>
          {" "}
          <Button onClick={closeModal}>取消</Button>{" "}
          <Button onClick={confirmModal}>确定</Button>{" "}
        </AtModalAction>
      </AtModal>
      <AtMessage />
    </View>
  );
};

export default Index;
